import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios'

export default class Search extends Component {

    componentDidMount() {

    }


    handlerSearch = () => {
        // 搜索前，更改当前状态
        PubSub.publish('search', {
            isFirst: false,
            isLoading: true
        })
        const url = `https://api.github.com/search/users?q=${this.searchText.value}`
        axios.get(url).then(
            res => {
                // 结束loading状态
                PubSub.publish('search', {
                    isLoading: false,
                    userList: res.data.items.map(v => {
                        return {
                            id: v.id,
                            avatar: v.avatar_url,
                            name: v.login,
                            home: v.html_url
                        }
                    })
                })
            },
            err => {
                // 请求失败后更新状态
                PubSub.publish('search', {
                    isLoading: false,
                    isError: err.message
                })
            })
    }

    render() {
        return (
            <div className="search">
                <h3>Search Github Users</h3>
                <input ref={c => this.searchText = c} type="text" />&nbsp;
                <button onClick={this.handlerSearch}>Search</button>
            </div>
        )
    }
}
